<?php
namespace api\modules\v1\models;

use api\components\ApiModel;
use common\models\AROrder;
use common\models\AROrderEvaluate;
use Yii;
use yii\helpers\ArrayHelper;
use common\models\ARUserScoring;
use common\models\ARBrokerScoring;

/**
 * 交易评价模型
 * @author ZCY
 */
class OrderEvaluate extends ApiModel
{
    const SCENARIO_CREATE = 'create';
    const SCENARIO_EVALUATE = 'evaluate';
    const SCENARIO_LIST = 'list';

    public $order_id;
    public $opp_uid1;
    public $opp_rating1;
    public $opp_appraise1;
    public $opp_uid2;
    public $opp_rating2;
    public $opp_appraise2;
    public $page;
    public $size;
    public $uid;

    private $orderInfo;

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'order_id'      => '订单编号',
            'opp_uid1'      => '对方用户1',
            'opp_rating1'   => '对方用户1评分',
            'opp_appraise1' => '对方用户1评价',
            'opp_uid2'      => '对方用户2',
            'opp_rating2'   => '对方用户2评分',
            'opp_appraise2' => '对方用户2评价',
            'size'          => '分页大小',
            'page'          => '当前页',
            'uid'           => '用户编号',

        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return [
            self::SCENARIO_CREATE   => ['order_id'],
            self::SCENARIO_EVALUATE => ['order_id', 'opp_uid1', 'opp_rating1', 'opp_appraise1', 'opp_uid2', 'opp_rating2', 'opp_appraise2'],
            self::SCENARIO_LIST     => ['page', 'size'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['order_id'], 'trim'],
            [['order_id', 'opp_uid1', 'opp_rating1', 'opp_uid2', 'opp_rating2', 'uid'], 'required'],
            [['opp_rating1', 'opp_rating2'], 'in', 'range' => [AROrderEvaluate::RATING_BAD, AROrderEvaluate::RATING_MEDIUM, AROrderEvaluate::RATING_GOOD]],
            [['opp_appraise1', 'opp_appraise2'], 'default', 'value' => '这个合作简直了!很是愉快!'],
            ['order_id', 'orderCheck'],
            ['size', 'default', 'value' => 10],
            ['page', 'default', 'value' => 1],
            [['size', 'page'], 'integer'],

        ];
    }

    /**
     * 订单编号检测
     * @param $attribute
     * @param $params
     */
    public function orderCheck($attribute, $params)
    {
        $orderInfo = AROrder::findOne(['id' => $this->attributes]);
        if (!$orderInfo) {
            $this->addError($attribute, '订单号不合法!');
        }
        $this->orderInfo = $orderInfo;
    }
    
    /**
     * 根据用户id获取好评率
     */
    private function getRating($uid){
        $totalrating=AROrderEvaluate::find()
                      ->where(['status'=>AROrderEvaluate::STATUS_COMPLETE,'opp_uid'=>$uid,['<','opp_identity',AROrderEvaluate::IDENTITY_BROKER]])
                      ->count();
        $goodrating=AROrderEvaluate::find()
                      ->where(['status'=>AROrderEvaluate::STATUS_COMPLETE,'opp_uid'=>$uid,'opp_rating'=>AROrderEvaluate::RATING_GOOD,['<','opp_identity',AROrderEvaluate::IDENTITY_BROKER]])
                      ->count();
        if($totalrating==0){
            return 0;
        }
        return $goodrating/$totalrating;
    }

    /**
     * 根据用户id获取经纪人好评率
     */
    private function getBrokerRating($uid){
        $totalrating=AROrderEvaluate::find()
        ->where(['status'=>AROrderEvaluate::STATUS_COMPLETE,'opp_uid'=>$uid,'opp_identity'=>AROrderEvaluate::IDENTITY_BROKER])
        ->count();
        $goodrating=AROrderEvaluate::find()
        ->where(['status'=>AROrderEvaluate::STATUS_COMPLETE,'opp_uid'=>$uid,'opp_rating'=>AROrderEvaluate::RATING_GOOD,'opp_identity'=>AROrderEvaluate::IDENTITY_BROKER])
        ->count();
        if($totalrating==0){
            return 0;
        }
        return $goodrating/$totalrating;
    }
    
    
    /**
     * 根据订单号产生评价
     */
    public static function create($orderInfo)
    {
        /*  if (!$this->validate()) {
        self::getErrorMessge($this);
        }  */
        /*    $orderInfo=AROrder::findOne(['id'=>$orderid,'status'=>AROrder::STATUS_SUCCESS]);
        if(!$orderInfo){
        self::throwError('500004');        //订单不存在
        } */
        $orderEvaluate = AROrderEvaluate::findOne(['order_id' => $orderInfo->id]);
        if ($orderEvaluate) {
            self::throwError('500001');
        }
        $time = Yii::$app->formatter->asTimestamp('now');

        if($orderInfo->broker){
            $evaluateItems = [
                ['order_id'  => $orderInfo->id, 'uid' => $orderInfo->uid,
                    'identity'   => AROrderEvaluate::IDENTITY_DEMAND, //需求方
                    'opp_uid'    => $orderInfo->opp_uid,
                    'opp_identity' => AROrderEvaluate::IDENTITY_APPLY,
                    'status'     => AROrderEvaluate::STATUS_NEED,
                    'created_at' => $time,
                    'updated_at' => $time,
                ],
                ['order_id'  => $orderInfo->id, 'uid' => $orderInfo->uid,
                    'identity'   => AROrderEvaluate::IDENTITY_DEMAND, //需求方
                    'opp_uid'    => $orderInfo->broker,
                    'opp_identity' => AROrderEvaluate::IDENTITY_BROKER,
                    'status'     => AROrderEvaluate::STATUS_NEED,
                    'created_at' => $time,
                    'updated_at' => $time,
                ],
                ['order_id'  => $orderInfo->id, 'uid' => $orderInfo->opp_uid,
                    'identity'   => AROrderEvaluate::IDENTITY_APPLY, //供应方
                    'opp_uid'    => $orderInfo->uid,
                    'opp_identity' => AROrderEvaluate::IDENTITY_DEMAND,
                    'status'     => AROrderEvaluate::STATUS_NEED,
                    'created_at' => $time,
                    'updated_at' => $time,
                ],
                ['order_id'  => $orderInfo->id, 'uid' => $orderInfo->opp_uid,
                    'identity'   => AROrderEvaluate::IDENTITY_APPLY, //供应方
                    'opp_uid'    => $orderInfo->broker,
                    'opp_identity' => AROrderEvaluate::IDENTITY_BROKER,
                    'status'     => AROrderEvaluate::STATUS_NEED,
                    'created_at' => $time,
                    'updated_at' => $time,
                ],
                ['order_id'  => $orderInfo->id, 'uid' => $orderInfo->broker,
                    'identity'   => AROrderEvaluate::IDENTITY_BROKER, //经纪人
                    'opp_uid'    => $orderInfo->uid,
                    'opp_identity' => AROrderEvaluate::IDENTITY_DEMAND,
                    'status'     => AROrderEvaluate::STATUS_NEED,
                    'created_at' => $time,
                    'updated_at' => $time,
                ],
                ['order_id'  => $orderInfo->id, 'uid' => $orderInfo->broker,
                    'identity'   => AROrderEvaluate::IDENTITY_BROKER, //经纪人
                    'opp_uid'    => $orderInfo->opp_uid,
                    'opp_identity' => AROrderEvaluate::IDENTITY_APPLY,
                    'status'     => AROrderEvaluate::STATUS_NEED,
                    'created_at' => $time,
                    'updated_at' => $time,
                ],
            
            ];
        }else{
            $evaluateItems = [
                ['order_id'  => $orderInfo->id, 'uid' => $orderInfo->uid,
                    'identity'   => AROrderEvaluate::IDENTITY_DEMAND, //需求方
                    'opp_uid'    => $orderInfo->opp_uid,
                    'opp_identity' => AROrderEvaluate::IDENTITY_APPLY,
                    'status'     => AROrderEvaluate::STATUS_NEED,
                    'created_at' => $time,
                    'updated_at' => $time,
                ],
                ['order_id'  => $orderInfo->id, 'uid' => $orderInfo->opp_uid,
                    'identity'   => AROrderEvaluate::IDENTITY_APPLY, //供应方
                    'opp_uid'    => $orderInfo->uid,
                    'opp_identity' => AROrderEvaluate::IDENTITY_DEMAND,
                    'status'     => AROrderEvaluate::STATUS_NEED,
                    'created_at' => $time,
                    'updated_at' => $time,
                ],           
            ];
        }

        $result = Yii::$app->db->createCommand()->batchInsert(AROrderEvaluate::tableName(), ['order_id', 'uid', 'identity', 'opp_uid','opp_identity', 'status', 'created_at', 'updated_at'], $evaluateItems)->execute();
        if (!$result) {
            self::throwError('500002');
        }

        return true;

    }

    /**
     * 评价
     */
    public function evaluate()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $transaction = Yii::$app->db->beginTransaction();
        $uid = Yii::$app->user->id;
        try {
            $orderevaluate1 = AROrderEvaluate::find()->where([
                'order_id' => $this->order_id,
                'uid'      => $uid,
                'opp_uid'  => $this->opp_uid1,
                'status'   => AROrderEvaluate::STATUS_NEED,
            ])->one();

            $orderevaluate2 = AROrderEvaluate::find()->where([
                'order_id' => $this->order_id,
                'uid'      => $uid,
                'opp_uid'  => $this->opp_uid2,
                'status'   => AROrderEvaluate::STATUS_NEED,
            ])->one();

            if (!$orderevaluate1 || !$orderevaluate2) {
                self::throwError('500003');
            }

            $orderevaluate1->opp_rating = $this->opp_rating1;
            $orderevaluate1->opp_appraise = $this->opp_appraise1;
            $orderevaluate1->status = AROrderEvaluate::STATUS_COMPLETE;
            if (!$orderevaluate1->save()) {
                self::getErrorMessge($orderevaluate1);
            }

            $orderevaluate2->opp_rating = $this->opp_rating2;
            $orderevaluate2->opp_appraise = $this->opp_appraise2;
            $orderevaluate2->status = AROrderEvaluate::STATUS_COMPLETE;
            if (!$orderevaluate2->save()) {
                self::getErrorMessge($orderevaluate2);
            }
            
            //更新用户评分表  好评率
            if($orderevaluate1->opp_identity==AROrderEvaluate::IDENTITY_BROKER){ //对方是经纪人身份
                $goodrating1=$this->getBrokerRating($orderevaluate1->opp_uid);
                $userscoring1=ARBrokerScoring::find()->where(['uid'=>$orderevaluate1->opp_uid])->one();
            }else{ 
                $goodrating1=$this->getRating($orderevaluate1->opp_uid);
                $userscoring1=ARUserScoring::find()->where(['uid'=>$orderevaluate1->opp_uid])->one();
            }
            
            if($orderevaluate2->opp_identity==AROrderEvaluate::IDENTITY_BROKER){ //对方是经纪人身份
                $goodrating2=$this->getBrokerRating($orderevaluate2->opp_uid);
                $userscoring2=ARBrokerScoring::find()->where(['uid'=>$orderevaluate2->opp_uid])->one();
            }else{
                $goodrating2=$this->getRating($orderevaluate2->opp_uid);
                $userscoring2=ARUserScoring::find()->where(['uid'=>$orderevaluate2->opp_uid])->one();
            }  
      
            if($userscoring1 && $userscoring2 ){
                $userscoring1->rating=$goodrating1;
                if (!$userscoring1->save()) {
                    self::getErrorMessge($userscoring1);
                }
                $userscoring2->rating=$goodrating2;
                if (!$userscoring2->save()) {
                    self::getErrorMessge($userscoring2);
                }
            }
                       
            $transaction->commit();
            return ['userId' => $uid];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 评价列表
     */
    public function evaluatelist()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $sql = AROrderEvaluate::find()->where(['opp_uid' => Yii::$app->user->id, 'status' => AROrderEvaluate::STATUS_COMPLETE])->with('user');
        $count = $sql->count();
        $data = $sql->limit($this->size)->offset($this->size * ($this->page - 1))->all();
        $row = ArrayHelper::toArray($data, [
            AROrderEvaluate::className() => [
                'nickname'     => function ($row) {
                    return $row->user->nickname;
                },
                'rating'       => 'opp_rating',
                'content'      => 'opp_appraise',
                'evaluatetime' => function ($row) {
                    return Yii::$app->formatter->asDatetime($row->updated_at);
                },
            ],
        ]);
        return ['count' => $count, 'row' => $row];
    }

}
